package net.documentshare;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.documentshare.docu.DocuUtils;
import net.documentshare.documentconfig.DocumentConfigMgr;
import net.documentshare.utils.IOUtils;
import net.documentshare.utils.doc.OfficeConverter;
import net.documentshare.utils.doc.PDFConverter;
import net.simpleframework.util.ConvertUtils;
import net.simpleframework.util.HTTPUtils;
import net.simpleframework.util.JSONUtils;

import org.apache.commons.lang3.StringUtils;
import org.artofsolving.jodconverter.office.OfficeConnectionProtocol;

import com.itextpdf.text.pdf.PdfReader;

@SuppressWarnings("serial")
public class DocumentshareMgr extends HttpServlet {

	@Override
	public void init(ServletConfig config) throws ServletException {
		initDoc(config);
		final String filePath = config.getServletContext().getRealPath("") + "/config/document.xml";
		DocumentConfigMgr.getDocuMgr().initDocuMgr(filePath);
	}

	public void initDoc(ServletConfig config) {
		Properties properties = new Properties();
		try {
			InputStream in = config.getServletContext().getResourceAsStream("/config/docviewer.properties");
			properties.load(in);
		} catch (Exception e2) {
			e2.printStackTrace();
		}
		String baseConfigSpace = "docviewer.";
		String baseConverterConfigSpace = baseConfigSpace + "converter.";
		String basePdfConfigSpace = baseConverterConfigSpace + "pdf.";
		String baseOfficeConfigSpace = baseConverterConfigSpace + "office.";

		try {
			OfficeConverter.setOfficeHome(new String(properties.getProperty(baseOfficeConfigSpace + "home", OfficeConverter.getOfficeHome())
					.getBytes("ISO-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		OfficeConverter.setPort(Integer.parseInt(properties.getProperty(baseOfficeConfigSpace + "port", OfficeConverter.getPort() + "")));
		String protocol = properties.getProperty(baseOfficeConfigSpace + "protocol");
		if (StringUtils.isNotBlank(protocol)) {
			protocol = protocol.toLowerCase();
			if (protocol.equals("socket")) {
				OfficeConverter.setConnectionProtocol(OfficeConnectionProtocol.SOCKET);
			} else if (protocol.equals("pipe")) {
				OfficeConverter.setConnectionProtocol(OfficeConnectionProtocol.PIPE);
			}
		}
		String profile = properties.getProperty(baseOfficeConfigSpace + "profile");
		if (StringUtils.isNotBlank(profile)) {
			OfficeConverter.setTemplateProfileDir(new File(profile));
		}

		try {
			OfficeConverter.startService();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		try {
			PDFConverter.setCommand(new String(properties.getProperty(basePdfConfigSpace + "command", PDFConverter.getCommand()).getBytes(
					"ISO-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		String max = properties.getProperty(basePdfConfigSpace + "mode.singlePage.maxThread", PDFConverter.getSinglePageModeMaxThread() + "");
		try {
			PDFConverter.setSinglePageModeMaxThread(Integer.parseInt(max));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			final String cmd = request.getParameter("cmd");
			final Map<String, String> json = new HashMap<String, String>();
			final String path = HTTPUtils.toLocaleString(request.getParameter("path"), "gbk");
			if ("create".equals(cmd)) {
				new File(path).mkdirs();
				json.put("act", "true");
			} else if ("convert".equals(cmd)) {
				final String docuFunction = request.getParameter("docuFunction");
				final String fileName = HTTPUtils.toLocaleString(request.getParameter("fileName"), "gbk");
				final String allowReads = request.getParameter("pages");
				final String convertPages = request.getParameter("convertPages");
				final String id = request.getParameter("id");
				DocuUtils.convertFile(path, fileName, docuFunction, id, ConvertUtils.toDouble(allowReads, 0), ConvertUtils.toInt(convertPages, 0),
						json);
				json.put("act", "true");
			} else if ("pages".equals(cmd)) {
				try {
					json.put("pages", String.valueOf(new PdfReader(path).getNumberOfPages()));
				} catch (Exception e) {
				}
				json.put("act", "true");
			} else if ("freeSpace".equals(cmd)) {
				try {
					final String diskSpace = request.getParameter("diskSpace");
					json.put("space", String.valueOf(new File(path).getFreeSpace() / 1024 / 1024 > ConvertUtils.toInt(diskSpace, 1024)));
				} catch (Exception e) {
				}
				json.put("act", "true");
			} else if ("delete".equals(cmd)) {
				try {
					IOUtils.delete(path);
				} catch (Exception e) {
				}
				json.put("act", "true");
			}
			final PrintWriter pw = response.getWriter();
			pw.append(JSONUtils.toJSON(json));
			pw.flush();
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}
}
